package com.company.demo;

import xyz.noark.core.annotation.Controller;
import xyz.noark.core.annotation.controller.*;
import xyz.noark.network.http.HttpServletRequest;

import java.util.Enumeration;

/**
 * HTTP服务入口.
 *
 * @author 小流氓[176543888@qq.com]
 */
@Controller
public class ApiController {

    /**
     * 无参示例
     */
    @ResponseBody
    @GetMapping(path = "/")
    public String index() {
        return "welcome to noark http service...";
    }

    /**
     * 常规参数示例
     */
    @ResponseBody
    @GetMapping(path = "/hello.php")
    public String hello(@RequestParam(name = "name") String name, @RequestParam(name = "age", required = false, defaultValue = "18") int age) {
        return "hello " + name + ", age=" + age;
    }

    /**
     * 注入request对象示例
     */
    @ResponseBody
    @GetMapping(path = "/hello.aspx")
    public String hello(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        sb.append("URI:\t\t").append(request.getUri()).append("\n");
        sb.append("method:\t\t").append(request.getMethod()).append("\n");
        sb.append("IP:\t\t").append(request.getRemoteAddr()).append("\n");

        sb.append("parameter----------").append("\n");
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String key = names.nextElement();
            sb.append(key).append("\t\t").append(request.getParameter(key)).append("\n");
        }
        return sb.toString();
    }

    /**
     * 注入对象示例，需要为自定义的对象编码转化器
     */
    @ResponseBody
    @GetMapping(path = "/hello.jsp")
    public String hello(@RequestParam(name = "item") SimpleItem item) {
        return "code=" + item.getCode() + ",num=" + item.getNum();
    }

    // -------------------以下需要使用在线网站发请求或写代码发请求测试啦--------------------------

    /**
     * 注入Json对象示例，注意这里请求是Post哈...
     * 客户端请求时需要增加这个头参数 "Content-Type", "application/json"
     */
    @ResponseBody
    @PostMapping(path = "/hello.do")
    public String postJson(@RequestParam(name = "code") String code, @RequestParam(name = "num") int num) {
        return "code=" + code + ", num=" + num;
    }

    /**
     * 直接POST一个内容，其他什么参数也没给，很是不科学的接口，但好多人在用啊.
     * <p>这里要注意，请求方的content-type没有才可以使用此方法</p>
     */
    @ResponseBody
    @PostMapping(path = "/hello.action")
    public String postContent(@RequestBody String jwtToken) {
        return "jwtToken=" + jwtToken;
    }
}